package oop.data;

import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import oop.db.dao.QuestionDAO;
import oop.db.dao.SectionQuestionAnswerDAO;
import oop.db.dao.SectionQuestionDAO;

public class Section {

	private long id;
	private String text;
	private int order;
	private int testId;
	private Map<Long, Question> questionMap = null;

	public Section(String text, int order) {
		this(0, text, order, 0);
	}

	public Section(long id, String text, int order, int testId) {
		this.id = id;
		this.text = text;
		this.order = order;
		this.testId = testId;
	}

	public Map<Long, Question> getQuestionById() throws SQLException {
		if (questionMap == null) {
			questionMap = new HashMap<Long, Question>();
			for (Question q : QuestionDAO.fetchBySection(id)) {
				questionMap.put(q.getId(), q);
			}
		}
		return questionMap;
	}

	public Collection<Question> getQuestions() throws SQLException {
		return getQuestionById().values();
	}
	
	public void addQuestion(Question question) throws SQLException {
		SectionQuestionDAO.addQuestion(id, question.getId());
		SectionQuestionAnswerDAO.addAnswers(id, question.getId(), 4);
		getQuestionById().put(question.getId(), question);
	}

	public void removeQuestion(Question question) throws SQLException {
		if (questionMap.containsValue(question)) {
			SectionQuestionAnswerDAO.removeAnswers(id, question.getId());
			SectionQuestionDAO.removeQuestion(id, question.getId());
			getQuestionById().remove(question.getId());
		}
	}

	public long getId() {
		return id;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public int getOrder() {
		return order;
	}

	public void setOrder(int order) {
		this.order = order;
	}
	
	public int getTestId() {
		return testId;
	}
	
	void setTestId(int testId) {
		this.testId = testId;
	}
	
}
